#include "MyString.h"
#include <cstring>
MyString::MyString():capacity(15),size(0)
{
    this->s = new char[this->capacity];
}

 MyString::MyString(const char*str)
 {
    this->size = strlen(str);
    this->capacity = this->size+1;
    this->s = new char[this->capacity];
    strcpy(this->s,str);
 }

MyString::~MyString()
{
    delete []this->s;
}

MyString::MyString(const MyString& str)
{
    this->size = str.size;
    this->capacity = str.capacity;
    this->s = new char[this->capacity];
    strcpy(this->s,str.s);
}

MyString& MyString::operator=(const MyString&str)
{
    delete []this->s;
    this->size = str.size;
    this->capacity = str.capacity;
    this->s = new char[this->capacity];
    strcpy(this->s,str.s);
    return *this;
}

 MyString& MyString::operator+=(const MyString& str)
 {
    this->size += str.size; //
    if(this->size >= this->capacity)
    {
        this->capacity = this->size + 1;
        char*newP = new char[this->capacity];
        strcpy(newP,this->s);
        delete []this->s;
        this->s = newP;
    }
    strcat(this->s,str.s);
    return *this;
 }

void MyString:: operator+=(const char& c)
{
    if(this->size >= this->capacity -1)
    {
        this->capacity *= 2;
        char*newP = new char[this->capacity];
        strcpy(newP,this->s);
        delete []this->s;
        this->s = newP;
    }
    this->s[this->size++] = c;
    this->s[this->size] = '\0';
}

 MyString MyString:: operator+(const MyString&str)
 {
    MyString result(*this);
    result += str;
    return result;
 }

 MyString & MyString:: operator-=(const MyString& str)
 {
    char* dest = strstr(this->s,str.s); //
    while(dest != nullptr)
    {
    char* back = dest + str.size;
    while(*back != '\0')
    {
        *dest++ = *back++;
    }
    *dest = '\0';
    this->size -=str.size;
    dest = strstr(this->s,str.s);
    }
    return*this;
 }

MyString MyString:: operator-(const MyString& str)
{
    MyString result(*this);
    result -=str;
    return result;
}

char& MyString:: operator[](int index)
{
    return this->s[index];
}

bool MyString:: operator==(const MyString& str)
{
    return strcmp(this->s,str.s) == 0;
} 

bool MyString::operator!=(const MyString& str)
{
    return strcmp(this->s,str.s) != 0;
}

bool MyString:: operator&&(const MyString& str)
{
    return this->size != 0 && str.size != 0;
}

std::ostream& operator<<(std::ostream&os,const MyString& str)
{
    os<<str.s;
    return os;
}

std::istream& operator>>(std::istream& is,MyString&str)
{   
    // char s[1024] = {0};
    // is>>s;
    // str = s;
    char c = 0;
    while((c = getchar()) != '\n') //把c等于缓冲区获取一个字符
    {
        str +=c; //逐个相加
    }
    return is;
}